<?php
/**
 * Created by IntelliJ IDEA.
 * User: HXL
 * Date: 2018/7/11
 * Time: 13:47
 */
namespace app\order\controller;

use think\Lang;
/**
 * 订单执行
 * Class Execorder
 * @package app\order\controller
 */
class Execorder extends Base{

    public function index(){
        $this->authVerify();
        //先从订单表中获取全部信息，mid，在由mid获取表号
        $field = "oid_exec,model_id,model_num,model_qty,model_start,model_end,meter_start,meter_end,order_num,assem_start,assem_end,mf_id,pid,order_cycle,assem_cycle,custom_tool,data_verify,sum_amounts,sum_units,is_status,oid,comments";
        $where = array();
        $orders = $this->orderexecs()->joinAll($where);
        $order = $this->resetOrdersExec($orders);
        $this->page($order);
        $this->asgModelTypes();
        $this->asgPrincs();
        $this->getOrders();
        $this->asgManus();
        $this->asgClients();
        $this->asgStates();
        //var_dump($order);exit();
        $this->assign('orderexecs', $order);
        return $this->fetch("eord/index");

    }


    /**
     * 添加action
     */
    public function save(){
        $this->authVerify();
        $orders = input("post.");
        //默认软件版本号、硬件版本号（在修改订单执行状态中由表计组添加）
        $orders['soft_version'] = '';
        $orders['hard_version'] = '';
        //是否有表号长度的限定
        $oid = $orders['oid'];
        $findOid = $this->orders()->findById(array('oid'=>$oid));

        $meterLen = $findOid['meter_len'];
        $startLen = strlen($orders['meter_start']);
        $endLen = strlen($orders['meter_end']);
        //1.表号长度限定了11或者13位，2.不确定表号长度  取消表号长度验证20181011
        /*if($meterLen != 0){
            $this->fixedMeterNum($orders, $meterLen);
        }else{
            //不确定表号长度验证,允许为空
            $this->verifyMeterNum($orders, $startLen, $endLen);
        }*/

        //5.如果是13位，只保留前面12位。
        /*if($startLen == 13){
            $orders['meter_start'] = substr($orders['meter_start'], 0, ($startLen-1));
        }
        if($endLen == 13){
            $orders['meter_end'] = substr($orders['meter_end'], 0, ($endLen-1));
        }*/
        $start = "1".$orders['meter_start'];
        $end = "1".$orders['meter_end'];
        //计算周期,只当生产状态为已完成时计算,日期需要判断
        $deliveryStatus = $findOid['deliver_status'];
        $orderCycle = $this->countDate($orders['model_start'], $orders['model_end']);
        $assemCycle = $this->countDate($orders['assem_start'], $orders['assem_end']);
        if(($orderCycle < 0) || ($assemCycle < 0)){
            return $this->error(Lang::get('enddate later than start'));
        }
        if($deliveryStatus == 0){
            $orders['order_cycle'] = $orderCycle;
            $orders['assem_cycle'] = $assemCycle;
        }else{
            $orders['order_cycle'] = 0;
            $orders['assem_cycle'] = 0;
        }

        $orders = $this->dealNull($orders);
        //var_dump($orders);exit();
        $orders['create_time_exec'] = date('Y-m-d H:i:s', time());
        $addOrder = $this->orderexecs()->add($orders, '');
        if($addOrder < 1){
            return $this->error(Lang::get('add fail'));
        }
        $lastId = $this->orderexecs()->lastSql();
        //是否有配件需要添加到客供料执行中
        //添加电子模块类型的客供料
        $addSupplies = $this->addSupplies($orders['model_id'], $lastId, $oid);

        return $this->success(Lang::get('add success'), 'Execorder/index');

    }


    /**
     * 修改action
     */
    public function esave(){
        $this->authVerify();
        $orders = input("post.");
        //订单号存在
        $oidExec = $orders['oid_exec'];
        $where = array('oid_exec'=>$oidExec);
        $find = $this->orderexecs()->findById($where);
        //更新之前获取更新之前的表号
        $meterStart = $find['meter_start'];
        $meterEnd = $find['meter_end'];
        if(!$find){
            return $this->error(Lang::get('order unexist'));
        }
        //是否有表号长度的限定
        $oid = $orders['oid'];
        $findOid = $this->orders()->findById(array('oid'=>$oid));

        $meterLen = $findOid['meter_len'];
        $startLen = strlen($orders['meter_start']);
        $endLen = strlen($orders['meter_end']);
        //1.表号长度限定了11或者13位，2.不确定表号长度  取消表号长度验证20181011
        /*if($meterLen != 0){
            $this->fixedMeterNum($orders, $meterLen);
        }else{
            //不确定表号长度验证,允许为空
            $this->verifyMeterNum($orders, $startLen, $endLen);
        }*/

        //5.如果是13位，只保留前面12位。
        /*if($startLen == 13){
            $orders['meter_start'] = substr($orders['meter_start'], 0, ($startLen-1));
        }
        if($endLen == 13){
            $orders['meter_end'] = substr($orders['meter_end'], 0, ($endLen-1));
        }*/
        $start = "1".$orders['meter_start'];
        $end = "1".$orders['meter_end'];
        //计算周期,只当生产状态为已完成时计算,日期需要判断
        $deliveryStatus = $findOid['deliver_status'];
        $orderCycle = $this->countDate($orders['model_start'], $orders['model_end']);
        $assemCycle = $this->countDate($orders['assem_start'], $orders['assem_end']);
        if(($orderCycle < 0) || ($assemCycle < 0)){
            return $this->error(Lang::get('enddate later than start'));
        }
        if($deliveryStatus == 0){
            $orders['order_cycle'] = $orderCycle;
            $orders['assem_cycle'] = $assemCycle;
        }else{
            $orders['order_cycle'] = 0;
            $orders['assem_cycle'] = 0;
        }

        $orders = $this->dealNull($orders);
        //添加电子模块类型的客供料
        $dealSupplies = $this->editSupplies($orders['model_id'], $oidExec, $oid);

        $edit = $this->orderexecs()->update($orders, $where);
        if($edit < 1){
            return $this->error(Lang::get('edit fail'));
        }
        return $this->success(Lang::get('edit success'), 'Execorder/index');

    }

    /**
     * 修改订单执行发货状态
     */
    public function esta(){
        $this->authVerify();
        $oidExec = input('param.oid_exec');
        $where = array('oid_exec'=>$oidExec);
        $find = $this->orderexecs()->findById($where);
        if(!$find){
            return $this->error(Lang::get('order unexist'));
        }
        $isStatus = input('param.is_status');
        $order['soft_version'] = input('param.soft_version');
        $order['hard_version'] = input('param.hard_version');
        $order['is_status'] = $isStatus;
        $order['data_verify'] = input('param.data_verify');
        $edit = $this->orderexecs()->update($order, $where);
        if($edit < 1){
            return $this->error(Lang::get('edit fail'));
        }
        return $this->success(Lang::get('edit success'), 'Execorder/index');
    }

    /**
     * json数据
     */
    public function one(){
        $oid = input('param.oid_exec');
        $field = "oid_exec,model_id,model_num,model_qty,model_start,model_end,meter_start,meter_end,order_num,assem_start,assem_end,mf_id,pid,order_cycle,assem_cycle,custom_tool,data_verify,sale_id,sum_amounts,sum_units,is_status,oid,comments,create_time_exec";
        $where = array('oid_exec'=>$oid);
        $data = $this->orderexecs()->joinSelect($where);
        $len = count($data);
        if($len > 0){
            //根据modelNum查询剩余模块数量
            $oneModel = $this->sumQty($data['0']['model_num']);
            $data['0']['surplus'] = $oneModel['model_qty'];
        }
        echo json_encode($data);
    }

    /**
     * json--发货状态
     */
    public function onestatus(){
        $oid = input('param.oid_exec');
        $where = array('oid_exec'=>$oid);
        $data = $this->orderexecs()->joinSelect($where);
        $data = $this->resetOrdersExec($data);
        echo json_encode($data);
    }

    /**
     * 删除action
     */
    public function del(){
        $this->authVerify();
        $oid = input('param.oid_exec');
        $where = array('oid_exec'=>$oid);
        $find = $this->orderexecs()->findById($where);
        if(!$find){
            return $this->error(Lang::get('order unexist'));
        }
        $del = $this->orderexecs()->del($where);
        if($del < 1){
            return $this->error(Lang::get('del fail'));
        }
        //删除订单执行时删除客供料执行
        $modelId = $find['model_id'];
        $this->delSupplies($modelId, $oid);

        return $this->success(Lang::get('del success'), 'Execorder/index');
    }

    /**
     * 查看详单
     */
    public function view(){
        $this->authVerify();
        //国家，客户，基表型号，电子模块类型，制造商，生产负责人，发货状态都是下拉框选择
        $oid = input('param.oid_exec');
        $order = $this->orderexecs()->joinSelect(array('oid_exec'=>$oid));
        $order = $this->resetOrderExec($order['0']);
        //基表型号
        $meterIds = $order['meter_id'];
        $meterIdArr = $this->stringToArr($meterIds);
        $orderQty = $order['order_qty'];
        $orderQtyArr = $this->stringToArr($orderQty);
        /*var_dump($meterIdArr);
        var_dump($orderQty);exit();*/
        $orderMeters = array();
        $len = count($meterIdArr);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $findMeter = $this->metertypes()->findById(array('meter_id'=>$meterIdArr[$i]));
                $orderMeters[$i] = array(
                    'meter_type'=>$findMeter['meter_type'],
                    'caliber'=>$findMeter['caliber'],
                    'm_num'=>$orderQtyArr[$i]
                );
            }
        }
//        var_dump($orderMeters);exit();
        $this->assign('ordermeters', $orderMeters);
        $this->assign('orderexec', $order);
        return $this->fetch("eord/view");
    }

    /**
     * 搜索
     */
    public function search(){
        $search = input('post.');
        //var_dump($search);exit();
        $deliverStatus = input('param.deliver_status');
        $meterNum = input('param.meter_num');
        $orderNum = input('param.order_num');
        $modelNum = input('param.model_num');
        $sid = input('param.sid');
        $cid = input('param.cid');
        $mfId = input('param.mf_id');
        $orders = $this->orderexecs()->search($meterNum, $deliverStatus, $sid, $cid, $orderNum, $modelNum, $mfId);
//        var_dump($orders);exit();
        $len = count($orders);
//        var_dump($len);exit();
        //存在搜索的结果
        if($len > 0){
            $orders = $this->resetOrdersExec($orders);
        }
//        var_dump($orders);exit();
        $this->page($orders);
        $this->asgModelTypes();
        $this->asgPrincs();
        $this->getOrders();
        $this->asgManus();
        $this->asgClients();
        $this->asgStates();
        //var_dump($order);exit();
        $this->assign('orderexecs', $orders);
        return $this->fetch("eord/index");

    }
    /**
     * 根据输入的模块订单号导入： 模块数量，模块下单开始时间和模块下单结束时间
     */
    public function getModelNum(){
        $modelNum = input('param.model_num');
        $modelNum = trim($modelNum);
        $oneModel = $this->sumQty($modelNum);
        echo json_encode($oneModel);
    }

    /**
     * 统计报表-按国家分类
     */
    public function gds(){
        $this->authVerify();
        $rate = 6.5;
        $newOrders = $this->graphS($rate);
        //var_dump($newOrders);exit();
        $this->assign('graphyS', $newOrders);
        return $this->fetch("eord/gds");
    }

    /**
     * 实时改变汇率，改变值--国家
     */
    public function jsonGraphS(){
        $rate = input('param.rate');
        $newOrders = $this->graphS($rate);
        echo $newOrders;
    }

    /**
     * 统计报表-按客户分类
     */
    public function gdc(){
        $this->authVerify();
        $rate = 6.5;
        $newOrders = $this->graphC($rate);
        //var_dump($newOrder);exit();
        $this->assign('graphyC', $newOrders);
        return $this->fetch("eord/gdc");
    }

    /**
     * 实时改变汇率，改变值--客户
     */
    public function jsonGraphC(){
        $rate = input('param.rate');
        $newOrders = $this->graphC($rate);
        echo $newOrders;
    }


    /**
     * 统计报表-按表型（基表型号）分类
     */
    public function gdm(){
        $this->authVerify();
        $rate = 6.5;
//        $newOrders = $this->graphM($rate);
        //按基表型号名称分类
        $newOrders = $this->graphyMeter($rate);
        //var_dump($newOrders);exit();
        $this->assign('graphyM', $newOrders);
        return $this->fetch("eord/gdm");
    }

    /**
     * 按基表型号分类的统计报表-基表型号名称
     */
    public function graphyMeter($rate){
        $orderExecs = $this->orderExecs()->graphMeter();
        $execLen = count($orderExecs);
        //去除没有基表型号的
        for($el=0;$el<$execLen;$el++){
            if($orderExecs[$el]['meter_id'] == ''){
                unset($orderExecs[$el]);
            }
        }
//        var_dump($orderExecs);exit();
        //由meterid获取meter_type,按最大数量的基表型号来统计
        $ordersGraphy = array();
        foreach ($orderExecs as $k=>$value){
            $ordersGraphy[$k] = $value;
            $meterIds = $value['meter_id'];
            $orderQtys = $value['order_qty'];
            $meterIdArr = $this->stringToArr($meterIds);
            $orderQtyArr = $this->stringToArr($orderQtys);
            $maxKV = $this->getMaxKeyV($orderQtyArr);
            $maxKey = $maxKV['0'];
            $meterId = $meterIdArr[$maxKey];
            $findMeter = $this->meterTypes()->findById(array('meter_id'=>$meterId));
            $ordersGraphy[$k]['meter_id'] = $meterId;
            $ordersGraphy[$k]['order_qty'] = $maxKV['1'];
            $ordersGraphy[$k]['meter_type'] = $findMeter['meter_type'];
            //1.将金额单位都换算成$符号的各订单金额总数
            if($ordersGraphy[$k]['sum_units'] == '$'){
                $ordersGraphy[$k]['value'] = $ordersGraphy[$k]['sum_amounts'] * $rate;
            }else{
                $ordersGraphy[$k]['value'] = $ordersGraphy[$k]['sum_amounts'];
            }

        }
        $newOrderGraphy = array();
        foreach ($ordersGraphy as $value){
            $newOrderGraphy[] = $value;
        }
        $newOrderGraphy = $this->assortArr($newOrderGraphy);
//        var_dump($newOrderGraphy);exit();
        $len = count($newOrderGraphy);
        //2.类型相同的金额总数
        $orderMeters = array();
        if($len > 0){
            for($i=0;$i<$len-1;$i++){
                $tmp = $newOrderGraphy[$i]['value'];
                if($newOrderGraphy[$i+1]['meter_type'] == $newOrderGraphy[$i]['meter_type']){
                    $newOrderGraphy[$i+1]['value'] += $tmp;
                    unset($newOrderGraphy[$i]);
                }
            }
        }
        //3.分类显示结果
        foreach ($newOrderGraphy as $k=>$value){
            $orderMeters[] = $newOrderGraphy[$k];
        }
//        var_dump($orderMeters);exit();
        return json_encode($orderMeters);

    }

    /**
     * 实时改变汇率改变值--基表型号
     */
    public function jsonGraphM(){
        $rate = input('param.rate');
        //按基表型号名称分类
        $newOrders = $this->graphyMeter($rate);
        echo $newOrders;
    }

    /**
     * 统计报表-按基表订单数量分类
     */
    public function gdq(){
        $this->authVerify();
        $newOrder = $this->orderQtyByMeter();
        $this->assign('graphQ', $newOrder);
        return $this->fetch("eord/gdq");

    }

    /**
     * 统计订单数量占比-按基表型号名称分类
     * @return string
     */
    private function orderQtyByMeter(){
        $orderExecs = $this->orderExecs()->graphMeter();
        //每个订单可能有好几个基表型号
        $meterQty = $this->reDealOrderqQty($orderExecs);
        $len = count($meterQty);
        //1.显示参数value=order_qty
        for($i=0;$i<$len;$i++){
            $meterQty[$i]['value'] = intval($meterQty[$i]['order_qty']);
        }
        $meterQty = $this->assortArr($meterQty);
//        var_dump($meterQty);exit();
        //2.相同基表型号的数量相加
        $orderMeters = array();
        for($j=0;$j<$len-1;$j++){
            $tmp = $meterQty[$j]['value'];
            if($meterQty[$j+1]['meter_type'] == $meterQty[$j]['meter_type']){
                $meterQty[$j+1]['value'] = $meterQty[$j+1]['value'] + $tmp;
                unset($meterQty[$j]);
            }
        }
//        var_dump($meterQty);exit();
        //3.顺序显示最后结果
        foreach ($meterQty as $k=>$value){
            $orderMeters[] = $meterQty[$k];
        }
//        var_dump($orderMeters);exit();
        return json_encode($orderMeters);
    }

    /**
     * 重组-按基表型号统计数量
     * @param $orderExecs
     * @return array
     */
    private function reDealOrderqQty($orderExecs){
        $orderGraphQ = array();
        //1.获取meter_type
        foreach ($orderExecs as $k=>$value){
            $orderGraphQ[$k] = $value;
            $meterIds = $value['meter_id'];
            $orderQtys = $value['order_qty'];
            $meterIdArr = $this->stringToArr($meterIds);
            $orderQtyArr = $this->stringToArr($orderQtys);
            $orderGraphQ[$k]['meter_id'] = $meterIdArr;
            $orderGraphQ[$k]['order_qty'] = $orderQtyArr;
            $meterTypeArr = array();
            foreach($meterIdArr as $key=>$meterId){
                $findMeter = $this->meterTypes()->findById(array('meter_id'=>$meterId));
                $meterTypeArr[$key] = $findMeter['meter_type'];
            }
            $orderGraphQ[$k]['meter_type'] = $meterTypeArr;
        }
        $len = count($orderGraphQ);
        $newOrders = array();
        //2.重组
        for($j=0;$j<$len;$j++){
            $meterLen = count($orderGraphQ[$j]['meter_id']);
            for($x=0;$x<$meterLen;$x++){
                $newOrders[$j][$x]['meter_id'] = $orderGraphQ[$j]['meter_id'][$x];
                $newOrders[$j][$x]['meter_type'] = $orderGraphQ[$j]['meter_type'][$x];
                $newOrders[$j][$x]['order_qty'] = $orderGraphQ[$j]['order_qty'][$x];
            }
        }
        //3.获取最后的显示结果
        $meterQty = array();
        foreach ($newOrders as $k=>$v){
            for($y=0;$y<count($v);$y++){
                $meterQty[] = $v[$y];
            }
        }
        return $meterQty;
    }

    /**
     * 表计组修改
     */
    public function editfor3(){
        $oid = input('param.oid_exec');
        $where = array('oid_exec'=>$oid);
        $find = $this->orderexecs()->findById($where);
        if(!$find){
            return $this->error(Lang::get('order unexist'));
        }
        $orders['custom_tool'] = input('param.custom_tool');
        $orders['data_verify'] = input('param.data_verify');
        $result = $this->orderexecs()->update($orders, $where);
        if($result < 1){
            return $this->error(Lang::get('edit fail'));
        }
        return $this->success(Lang::get('edit success'), 'Execorder/index');

    }

    /**
     * 导出订单执行列表-- 20190515
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function export(){
        $this->authVerify();
        $data = $this->orderexecs()->joinSelect(array());
        //数据处理
        $data = $this->setData($data);
        $excel = new ExportExcel();
        return $excel->exportExecOrder($data);
    }
    /**
     * 每一个基表型号的订单总数
     * @param $newOrder
     * @return mixed  $order[meterId][orderQty]
     */
    private function allQty($newOrder){
        $meterIds = array_column($newOrder, 'meter_id');
        array_multisort($meterIds, SORT_ASC, $newOrder);
        $len = count($newOrder);
        $orders[$newOrder['0']['meter_id']]['0'] = $newOrder['0']['order_qty'];
        for($i=0;$i<$len;$i++){
            $meterId = $newOrder[$i]['meter_id'];
            //按照id分类
            $orders[$meterId][$i] = $newOrder[$i]['order_qty'];
        }
        $lenOrder = count($orders);
        //$orders['0']['sum'] = 0;
        foreach ($orders as $meterId=>$value){
            $sum = 0;
            foreach ($value as $v){
                $sum += $v;
            }
            $value = $sum;
            $orders[$meterId] = $value;
        }
        return $orders;
    }

    /**
     * 基表型号主类的订单数量
     * $orders[key]=>{meterid,metertype,value}
     */
    private function qtyByMeterId($orders){
        $newOrder = array();
        foreach ($orders as $meterId=>$orderQty){
            //判断是否是主类
            $find = $this->meterTypes()->findById(array('meter_id'=>$meterId));
            $pid = $find['pid'];
            //判断是否主类
            //如果是主类，直接输出
            //如果不是主类，找到主类meterId,分类的订单金额
            if($pid == 0){
                $newOrder[$meterId]['meter_id'] = $meterId;
                $newOrder[$meterId]['meter_type'] = $find['meter_type'];
                $newOrder[$meterId]['value']['0'] = $orderQty;
            }else{
                $newOrder[$pid]['meter_id'] = $pid;
                $findNew = $this->meterTypes()->findById(array('meter_id'=>$pid));
                $newOrder[$pid]['meter_type'] = $findNew['meter_type'];
                $newOrder[$pid]['value'][$meterId] = $orderQty;
            }

        }
        $newOrders = array();
        foreach ($newOrder as $meterId=>$v){
            $sum = 0;
            foreach ($v['value'] as $value){
                $sum += $value;
            }
            $newOrders[] = array(
                'meter_id'=>$v['meter_id'],
                'meter_type'=>$v['meter_type'],
                'value'=>$sum
            );
        }
        return $newOrders;
    }

    ///////////////////////////

    /**
     * 表号验证，允许都为空，也可以结束表号单为空
     * @param $orders
     * @param $startLen
     * @param $endLen
     */
    private function verifyMeterNum($orders, $startLen, $endLen){
        //表号验证,允许为空
        ////1.长度10,,11,12,13;2.长度相等；3.前四位相同;4.都是数字；5.如果是13位，只保留前面12位。
        if($startLen > 0){
            if(($startLen < 10) || ($startLen > 13)){
                return $this->error(Lang::get('only 10 11 12 13 long'));
            }
            //开始表号和结束表号都存在
            if($endLen > 0){
                $this->verifyNum($orders['meter_start'], $orders['meter_end']);
            }

        }else if($endLen > 0){
            //不允许只有结束表号
            return $this->error(Lang::get('only start unallowed'));
        }
    }
    /**
     * 验证表号(开始表号和结束表号都存在)
     */
    private function verifyNum($startNum, $endNum){
        //1.长度10,,11,12,13;2.长度相等；3.前四位相同;4.都是数字；5.如果是13位，只保留前面12位。
        $startLen = strlen($startNum);
        $endLen = strlen($endNum);
        $start4 = substr($startNum, 0, 4);
        $end4 = substr($endNum, 0, 4);
        $startIsNum = is_numeric($startNum);
        $endIsNum = is_numeric($endNum);
        if(($startLen != $endLen) || ($start4 != $end4) || (!$startIsNum) || (!$endIsNum)){
            return $this->error(Lang::get('number and four the same'));
        }
        $startFloat = floatval($startNum);
        $endFloat = floatval($endNum);
        $intLength = intval($endFloat-$startFloat);
        //var_dump($intLength);exit();
        if($intLength < 1){
            return $this->error(Lang::get('end bigger than start'));
        }

    }
    /**
     * 固定11或13位表号的判断
     * @param $orders
     * @param $meterLen
     */
    private function fixedMeterNum($orders, $meterLen){
        $startLen = strlen($orders['meter_start']);
        $endLen = strlen($orders['meter_end']);
        if($startLen > 0){
            if($startLen != $meterLen){
                return $this->error(Lang::get('only '.$meterLen.' long'));
            }
            //开始表号和结束表号都存在
            if($endLen > 0){
                $this->verifyNum($orders['meter_start'], $orders['meter_end']);
            }
        }else if($endLen > 0){
            //不允许只有结束表号
            return $this->error(Lang::get('only start unallowed'));
        }
    }
    /**
     * 日期计算-》周期(单位：日)
     */
    private function countDate($start, $end){
        //如果结束时间为空，直接返回true
        if($end == ''){
            return 0;
        }
        //刚开始格式为2018-05-10
        $startDate = strtotime($start);
        $endDate = strtotime($end);
        $days = round(($endDate-$startDate)/3600/24) ;
        return $days;
    }

    /**
     * 获取剩余模块数量
     * @return array
     */
    private function sumQty($modelNum){
        $where = array('model_num'=>$modelNum);
        //订单号升序
        $order = 'create_time_exec asc';
        $select = $this->orderexecs()->joinOrder($where, $order);
        //var_dump($select);exit();
        $len = count($select);
        $sum = 0;
        //剩余量
        $surplus = 0;
        $oneModel = array(
            'model_qty' => $surplus,
            'model_start' => '',
            'model_end' => '',
            'firstadd' =>'请输入模块总数量'
        );
        if($len>0){
            //1.获取第一个订单号的模块数量和订单数量
            $nums = $select['0']['model_qty'];
            //$orderQty = $select['0']['order_qty'];
            //订单数量有的会有括号，需要做处理
            //$orderQty = $this->dealBraces($orderQty);
            //2.循环输出每一个订单的订单数量总和
            for ($i=0;$i<$len;$i++){
                $everyQty = $select[$i]['order_qty'];
                $everyQty = $this->dealBraces($everyQty);
                $sum += $everyQty;
            }
            //3.导出最后的剩余量（总的模块数量减去用掉的订单数量）
            $surplus = $nums - $sum;
            $firstadd = '';
            $start = $select['0']['model_start'];
            $end = $select['0']['model_end'];
            //传给前端的数据
            $oneModel = array(
                'model_qty' => $surplus,
                'model_start' => $start,
                'model_end' => $end,
                'firstadd' => $firstadd
            );
        }
        return $oneModel;
    }

    /**
     * 订单数量不是数字的处理（括号处理）
     */
    private function dealBraces($orderQty){
        //先判断是否包含括号(中英文格式都要判断)
        $start = 0;
        $end = 0;
        //1.英文开头
        $eStart = strpos($orderQty, '(');
        if($eStart){
            $start = $eStart;
        }
        //2.英文结束
        $eEnd = strpos($orderQty, ')');
        if($eEnd){
            $end = $eEnd;
        }
        //3.中文开头
        $zStart = strpos($orderQty, '（');
        if($zStart){
            //将中英文字符替换
            $orderQty = str_replace('（', '(', $orderQty);
            $start = strpos($orderQty, '(');
        }
        //4.中文结束
        $zEnd = strpos($orderQty, '）');
        if($zEnd){
            //将中英文字符替换
            $orderQty = str_replace('）', ')', $orderQty);
            $end = strpos($orderQty, ')');
        }
        if($start && $end){
            $len = $end-$start-1;
            $orderQty = substr($orderQty, $start+1, $len);
        }
        return $orderQty;
    }
    //获取json值
    private function graphS($rate){
        //默认rate用6.5表示
        //$rate = input('param.rate');
        //一维数组
        $orders = $this->groupSid($rate);
        $len = count($orders);
        //var_dump($orders);exit();
        $newOrder = array();
        if($len > 0){
            $i=0;
            foreach ($orders as $sid=>$sumAmounts){
                $findSid = $this->states()->findById(array('sid'=>$sid));
                $newOrder[$i]['sid'] = $sid;
                $newOrder[$i]['state'] = $findSid['state'];
                $newOrder[$i]['value'] = number_format($sumAmounts, 2);
                //去除分隔符
                $newOrder[$i]['value'] = str_replace(',', '', $newOrder[$i]['value']);
                $i++;
            }
        }
        $newOrders = json_encode($newOrder);
        return $newOrders;
    }

    /**
     * 按国家计算总金额
     * @param $rate
     * @return array
     */
    private function groupSid($rate){
        $orders = $this->calSumByRate($rate);
        //var_dump($orders);exit();
        $len = count($orders);
        $sameSid = array();
        if($len > 0){
            $firstSid = $orders['0']['sid'];
            $sameSid[$firstSid]['0'] = $orders['0']['sum_amounts'];
            for($i=1;$i<$len;$i++){
                if($orders[$i]['sid'] == $orders[$i-1]['sid']){
                    $sid = $orders[$i-1]['sid'];
                    $sameSid[$sid][] = $orders[$i]['sum_amounts'];
                }else{
                    $sid = $orders[$i]['sid'];
                    $sameSid[$sid][]  = $orders[$i]['sum_amounts'];
                }
            }
            $sum = array();
            foreach ($sameSid as $sid=>$sumAmount){
                $sumSid = 0.00;
                for($j=0;$j<count($sumAmount);$j++){
                    $sumSid += $sumAmount[$j];
                }
                $sum[$sid] = $sumSid;
            }
        }else{
            $sum = array();
        }

        //var_dump($sum);exit();
        return $sum;
    }
    //json--客户
    private function graphC($rate){
        //默认rate用6.5表示
        //$rate = input('param.rate');
        //一维数组
        $orders = $this->groupCid($rate);
        $len = count($orders);
        $newOrder = array();
        if($len > 0){
            $i=0;
            foreach ($orders as $cid=>$sumAmounts){
                $findCid = $this->clients()->findById(array('cid'=>$cid));
                $newOrder[$i]['cid'] = $cid;
                $newOrder[$i]['client'] = $findCid['client'];
                $newOrder[$i]['value'] = number_format($sumAmounts, 2);
                //去除分隔符
                $newOrder[$i]['value'] = str_replace(',', '', $newOrder[$i]['value']);
                $i++;
            }
        }
        $newOrders = json_encode($newOrder);
        return $newOrders;
    }

    /**
     * 按客户计算总金额
     * @param $rate
     * @return array
     */
    private function groupCid($rate){
        $orders = $this->calSumByRate($rate);
        //var_dump($orders);
        $len = count($orders);
        $sameCid = array();
        if($len > 0) {
            $firstCid = $orders['0']['cid'];
            $sameCid[$firstCid]['0'] = $orders['0']['sum_amounts'];
            for ($i = 1; $i < $len; $i++) {
                if ($orders[$i]['cid'] == $orders[$i - 1]['cid']) {
                    $cid = $orders[$i - 1]['cid'];
                    $sameCid[$cid][] = $orders[$i]['sum_amounts'];
                } else {
                    $cid = $orders[$i]['cid'];
                    $sameCid[$cid][] = $orders[$i]['sum_amounts'];
                }
            }
            $sum = array();
            foreach ($sameCid as $cid => $sumAmount) {
                $sumCid = 0.00;
                for ($j = 0; $j < count($sumAmount); $j++) {
                    $sumCid += $sumAmount[$j];
                }
                $sum[$cid] = $sumCid;
            }
        }else{
            $sum = array();
        }
        //var_dump($sum);exit();
        return $sum;
    }
    //json--基表型号
    private function graphM($rate){
        //默认rate用6.5表示
        //$rate = input('param.rate');
        //一维数组
        $orders = $this->groupMeterId($rate);
        //var_dump($orders);exit();
        $len = count($orders);
        $newOrder = array();
        if($len > 0){
            $i=0;
            foreach ($orders as $meterId=>$sumAmounts){
                $findMeterId = $this->meterTypes()->findById(array('meter_id'=>$meterId));
                $pid = $findMeterId['pid'];
                //判断是否主类
                //如果是主类，直接输出
                //如果不是主类，找到主类meterId,分类的订单金额
                if($pid == 0){
                    $newOrder[$meterId]['meter_id'] = $meterId;
                    $newOrder[$meterId]['meter_type'] = $findMeterId['meter_type'];
                    $newOrder[$meterId]['value']['0'] = number_format($sumAmounts, 2);
                    //去除分隔符
                    $newOrder[$meterId]['value']['0'] = str_replace(',','', $newOrder[$meterId]['value']['0']);
                }else{
                    $newOrder[$pid]['meter_id'] = $pid;
                    $findNew = $this->meterTypes()->findById(array('meter_id'=>$pid));
                    $newOrder[$pid]['meter_type'] = $findNew['meter_type'];
                    $newOrder[$pid]['value'][$meterId] = number_format($sumAmounts, 2);
                    //去除分隔符
                    $newOrder[$pid]['value'][$meterId] = str_replace(',', '', $newOrder[$pid]['value'][$meterId]);
                }

            }
            //var_dump($newOrder);exit();
            //继续做处理，计算各类订单value
            foreach ($newOrder as $meterId=>$value){
                $everyValue = $value['value'];
                //var_dump($everyValue);
                $tempSumValue = 0;
                foreach ($everyValue as $v){
                    $tempSumValue += $v;
                }
                //var_dump($tempSumValue);
                $value['value'] = number_format($tempSumValue, 2);
                //去除分隔符
                $value['value'] = str_replace(',', '', $value['value']);
                $tempOrder[] = $value;
            }
            //需要重新组合
            $newOrder = $tempOrder;
        }
        //var_dump($newOrder);exit();
        $newOrders = json_encode($newOrder);
        return $newOrders;
    }
    /**
     * 按基表型号计算总金额
     * @param $rate
     * @return array
     */
    private function groupMeterId($rate){
        $orders = $this->calSumByRate($rate);
        //var_dump($orders);exit();
        //var_dump($orders);
        $len = count($orders);
        //同一个基表型号属于一类
        $sameMeterId = array();
        if($len > 0){
            $firstMeterId = $orders['0']['meter_id'];
            $sameMeterId[$firstMeterId]['0'] = $orders['0']['sum_amounts'];
            for($i=1;$i<$len;$i++){
                if($orders[$i]['meter_id'] == $orders[$i-1]['meter_id']){
                    $meterId = $orders[$i-1]['meter_id'];
                    $sameMeterId[$meterId][] = $orders[$i]['sum_amounts'];
                }else{
                    $meterId = $orders[$i]['meter_id'];
                    $sameMeterId[$meterId][]  = $orders[$i]['sum_amounts'];
                }
            }
            $sum = array();
            foreach ($sameMeterId as $meterId=>$sumAmount){
                $sumMeterId = 0.00;
                for($j=0;$j<count($sumAmount);$j++){
                    $sumMeterId += $sumAmount[$j];
                }
                $sum[$meterId] = $sumMeterId;
            }
        }else{
            $sum = array();
        }
        //var_dump($sum);exit();
        return $sum;
    }

    /**
     * 通过汇率计算总金额（人民币元）
     * @param $rate
     */
    private function calSumByRate($rate){
        //汇率转换成number
        $rate = floatval($rate);
        //$field = 'oid,sid,cid,meterId,sumUnits,sum_amounts';
        $where = '';
        $order = 'oid_exec asc';
        $orders = $this->orderexecs()->joinSidOrder($where, $order);
        //var_dump($orders);exit();
        $len = count($orders);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                if($orders[$i]['sum_units'] == '$'){
                    $temp = floatval($orders[$i]['sum_amounts'] * $rate);
                    $orders[$i]['sum_amounts'] = $temp;

                }else{
                    $temp = floatval($orders[$i]['sum_amounts']);
                    $orders[$i]['sum_amounts'] = $temp;
                }
            }
        }
        //var_dump($orders);exit();
        return $orders;
    }
    /**
     * 去除数据前后空格
     * @param $orders
     * @return mixed
     */
    private function dealNull($orders){
        $orders['model_num'] = trim($orders['model_num']);
        $orders['order_num'] = trim($orders['order_num']);
//        $orders['sum_amounts'] = trim($orders['sum_amounts']);
        return $orders;
    }

    /**
     * 二位数组获取
     * @param $orders
     */
    public function resetOrdersExec($orders){
        $len = count($orders);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $orders[$i] = $this->resetOrderExec($orders[$i]);
            }
        }
        return $orders;
    }

    /**
     * 一维数组获取
     * @param $order
     * @return mixed
     */
    private function resetOrderExec($order){
        $len = count($order);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $saleId = $order['sale_id'];
//                var_dump($saleId);exit();
                $deliveryStatus = $order['deliver_status'];
                $order['delivery_status'] = $this->getStatus($deliveryStatus);
                $order['sale'] = $this->setSaleDepts($saleId);
                //客户化工具，生产数据检验
                $order['custom'] = $this->isOrNo($order['custom_tool']);
                $order['data'] = $this->isOrNo($order['data_verify']);

            }

        }else{
            $order['delivery_status'] = '';
            $order['sale'] = '';
            $order['custom'] = '';
            $order['data'] = '';
        }
        return $order;
    }
    /**
     * 获取未被评审的评审订单号
     */
    private function getOrders(){
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status";
        $where = array('parent_id'=>0);
        //只显示主表订单
        $orders = $this->orders()->joinAll($where);
        //去除已经在订单执行表中出现的订单评审号
        $orderExec = $this->orderexecs()->select('oid');
        $oids = array();
        for($i=0;$i<count($orderExec);$i++){
            $oids[$i] = $orderExec[$i]['oid'];
        }
        $newOrders = array();
        for($j=0;$j<count($orders);$j++){
            if(!in_array($orders[$j]['oid'], $oids, false)){
                $newOrders[$j]['oid'] = $orders[$j]['oid'];
            }
        }
        $this->assign('orders', $newOrders);
    }
    public function test(){
        $modelId = 10;
        $oidexec = 7;
        $oid = 12;
        $re = $this->addNewSupplies($modelId, $oidexec, $oid);
    }
    /**
     * 批量添加客供料采购信息
     * @param $modelId
     * @param $oidexec
     * @param $oid
     * @return int|string
     */
    private function addSupplies($modelId, $oidexec, $oid){
        //当前模块型号的客供料
        $where = array('mod_id'=>$modelId);
        $supplies = $this->supplies()->select('*', $where);
        $suppliesLen = count($supplies);
        //1.订单审核中是否包括是CIU的配件，包括则需要添加，反之不添加
        $fids = $this->orders()->select('*', array('parent_id'=>$oid));
        $fidArr = array();
        $fidsLen = count($fids);
        if($fidsLen > 0){
            for($j=0;$j<$fidsLen;$j++){
                $fidArr[$j] = $fids[$j]['fid'];
                $findFid = $this->fittings()->findById(array('fid'=>$fidArr[$j]));
                if($findFid['is_ciu'] == 0){
                    unset($fidArr[$j]);
                }
            }
        }
//        var_dump($fidArr);exit();
        //客供料执行：1.电子模块类型的客供料；2.配件的客供料。
        $modelSupplies = array();
        for($i=0;$i<$suppliesLen;$i++){
            $modelSupplies[$i]['fitid'] = $supplies[$i]['fit_id'];
            $modelSupplies[$i]['supid'] = $supplies[$i]['sup_id'];
            $modelSupplies[$i]['modelid'] = $supplies[$i]['mod_id'];
            $modelSupplies[$i]['product_status'] = '0';
            $modelSupplies[$i]['oidexec'] = $oidexec;
        }
//        var_dump($modelSupplies);exit();
        //有是CIU的配件时
        $fidArrLen = count($fidArr);
        $fitIdArr = array();
        if($fidArrLen > 0){
            foreach ($fidArr as $fitId){
                //1.找出该配件对应的客供料
                $eachFid = $this->supplies()->select('*', array('fit_id'=>$fitId));
                if(count($eachFid) > 0){
                    foreach ($eachFid as $ke=>$value){
                        if($value['mod_id'] == $modelId){
                            unset($eachFid[$ke]);
                        }/*else{
                            $value['fitid'] = $value['fit_id'];
                            $value['supid'] = $value['sup_id'];
                            $value['modelid'] = $value['mod_id'];
                            $value['product_status'] = '0';
                            $value['oidexec'] = $oidexec;
                            $eachFid[$ke] = $value;
                        }*/
                    }
                }
               //2.组合 到一个arr中
                $fitIdArr[] = $eachFid;
            }
        }
        $newTmp = $this->arr3To2($fitIdArr);
//        var_dump($newTmp);exit();
        $newLen = count($newTmp);
        if($newLen > 0){
            $modelLen = count($modelSupplies);
            for($m=0;$m<$newLen;$m++){
                $modelSupplies[$modelLen]['fitid'] = $newTmp[$m]['fit_id'];
                $modelSupplies[$modelLen]['supid'] = $newTmp[$m]['sup_id'];
                $modelSupplies[$modelLen]['modelid'] = $newTmp[$m]['mod_id'];
                $modelSupplies[$modelLen]['product_status'] = '0';
                $modelSupplies[$modelLen]['oidexec'] = $oidexec;
                $modelLen++;
            }
        }
//        var_dump($modelSupplies);exit();
        $insertAll = $this->modelSupplies()->insertAll($modelSupplies);
        return $insertAll;
    }

    /**
     * 修改订单执行时修改客供料采购状态
     * @param $modelId
     * @param $oidExec
     * @param $oid
     */
    private function editSupplies($modelId, $oidExec, $oid){
        //1.判断是否和之前的modelid相同
        $isCom = $this->modelSupplies()->findById(array('modelid'=>$modelId, 'oidexec'=>$oidExec));
        //2.不相同，删除原来的客供料采购信息,添加新的
        if(!$isCom){
            $del = $this->modelSupplies()->del(array('oidexec'=>$oidExec));
            $add = $this->addSupplies($modelId, $oidExec, $oid);
        } else{
            //3.相同，看看是否有新的客供料需要添加,在订单执行之后添加的客供料 TODO
            $addNew = $this->addNewSupplies($modelId, $oidExec, $oid);
        }

    }

    /**
     * 删除订单执行时删除客供料执行，修改时添加在订单执行之后添加的客供料
     * @param $modelId
     * @param $oidExec
     */
    private function delSupplies($modelId, $oidExec){
        $where = array('modelid'=>$modelId, 'oidexec'=>$oidExec);
        $del = $this->modelSupplies()->del($where);
    }

    public function test1(){
        $modelId = 2;
        $oidExec = 8;
        $oid = 30;
        return $this->addNewSupplies($modelId, $oidExec, $oid);
    }
    /**
     * 是否有新的客供料需要添加
     * @param $modelId
     * @param $oidExec
     * @return int|string
     */
    private function addNewSupplies($modelId, $oidExec, $oid){
        $isCom = $this->modelSupplies()->select('*', array('modelid'=>$modelId, 'oidexec'=>$oidExec));
        $supplies = $this->supplies()->select('*', array('mod_id'=>$modelId));
        $allSupIds = array();
        for($j=0;$j<count($isCom);$j++){
            $allSupIds[$j] = $isCom[$j]['supid'];
        }
        //1.订单审核中是否包括是CIU的配件，包括则需要添加，反之不添加
        $fids = $this->orders()->select('*', array('parent_id'=>$oid));
        $fidArr = array();
        $fidsLen = count($fids);
        if($fidsLen > 0){
            for($j=0;$j<$fidsLen;$j++){
                $fidArr[$j] = $fids[$j]['fid'];
                $findFid = $this->fittings()->findById(array('fid'=>$fidArr[$j]));
                if($findFid['is_ciu'] == 0){
                    unset($fidArr[$j]);
                }
            }
        }
        $newSupplies = array();
        //需要修改的，只添加新的
        $editSupplies = array();
        for($i=0;$i<count($supplies);$i++){
            //有新的客供料(订单执行后添加的客供料)
            if(!in_array($supplies[$i]['sup_id'], $allSupIds, false)){
                $newSupplies[$i]['supid'] = $supplies[$i]['sup_id'];
                $newSupplies[$i]['modelid'] = $supplies[$i]['mod_id'];
                $newSupplies[$i]['product_status'] = '0';
                $newSupplies[$i]['fitid'] = $supplies[$i]['fit_id'];
                $newSupplies[$i]['oidexec'] = $oidExec;
            }
        }
        //将该数组排序
        $newSupplies = $this->sortArr($newSupplies);
        //有是CIU的配件时
        $fidArrLen = count($fidArr);
        $fitIdArr = array();
        if($fidArrLen > 0){
            foreach ($fidArr as $fidArrKey=>$fitId){
                //1.找出该配件对应的客供料
                $eachFid = $this->supplies()->select('*', array('fit_id'=>$fitId));
                if(count($eachFid) > 0){
                    foreach ($eachFid as $ke=>$value){
                        if($value['mod_id'] == $modelId){
                            unset($eachFid[$ke]);
                        }
                    }
                }
                //2.组合 到一个arr中
                $fitIdArr[$fidArrKey] = $eachFid;
            }
        }
        $newTmp = $this->arr3To2($fitIdArr);
        //是否已经存在数据库中
        foreach ($newTmp as $newKey=>$newCiu){
            $find = $this->modelSupplies()->findById(array('supid'=>$newCiu['sup_id'], 'modelid'=>$newCiu['mod_id'],'fitid'=>$newCiu['fit_id']));
            if($find){
                unset($newTmp[$newKey]);
            }
        }
        $newLen = count($newTmp);
        if($newLen > 0){
            $modelLen = count($newSupplies);
            for($m=0;$m<$newLen;$m++){
                $newSupplies[$modelLen]['fitid'] = $newTmp[$m]['fit_id'];
                $newSupplies[$modelLen]['supid'] = $newTmp[$m]['sup_id'];
                $newSupplies[$modelLen]['modelid'] = $newTmp[$m]['mod_id'];
                $newSupplies[$modelLen]['product_status'] = '0';
                $newSupplies[$modelLen]['oidexec'] = $oidExec;
                $modelLen++;
            }
        }
        $insertNew = $this->modelSupplies()->insertAll($newSupplies);
        return $insertNew;
    }

    /**
     * 三维数组转二维数组
     * @param $arr
     * @return array
     */
    private function arr3To2($arr){
        $i=0;
        $newArr = array();
        foreach ($arr as $key=>$value){
            foreach ($value as $k=>$v){
                $newArr[$i] = $v;
                $i++;
            }
        }
        return $newArr;
    }

    private function setData($data){
        for($k=0;$k<count($data);$k++){
            //客户，基表型号，电子模块类型
            $clients = $this->clients()->findById(array('cid'=>$data[$k]['cid']));
            $meterTypes = $this->meterTypes()->findById(array('meter_id'=>$data[$k]['meter_id']));
            $modelTypes = $this->modelTypes()->findById(array('model_id'=>$data[$k]['model_id']));
            $data[$k]['client'] = $clients['client'];
            $data[$k]['meter_type'] = $meterTypes['meter_type'];
            $data[$k]['model_type'] = $modelTypes['model_type'];
            switch ($data[$k]['sale_id']){
                case 1:
                    $data[$k]['sale'] = "业务一部";
                    break;
                case 2:
                    $data[$k]['sale'] = "业务二部";
                    break;
                case 3:
                    $data[$k]['sale'] = "业务三部";
                    break;
                case 4:
                    $data[$k]['sale'] = "业务四部";
                    break;
                default:
                    break;
            }
            unset($data[$k]['cid']);
            unset($data[$k]['meter_id']);
            unset($data[$k]['model_id']);
        }
        return $data;
    }
}